Ccay.Module.define("ccay.security.user.EditAuthorization2User", function(page, $S) {
	//var request=Ccay.Page.getRequest();
	var userMaxDay = 365;
	var initTime = new Date();
	var overdueDay = 7;
	var authorization2userGrid;
	/**
	 * 显示角色名
	 */
	page.showRoleName = function(roleId,roleName) {
		return roleName?Ccay.UI.button(roleName.encode(),"ccay.security.user.EditAuthorization2User.openRolePermissionView('{0}')".formatValue(roleId)
				,"","link",""):"";
	};
	/**
	 * 显示Program+Program无效时的图标
	 */
	page.showProgramName = function(programId,programName) {
		return programName?Ccay.UI.button(programName.encode(),"ccay.security.user.EditAuthorization2User.openProgramView('{0}')".formatValue(programId)
			,"","link","") : "";
	};
	
	page.init = function(userId) {
		loadUserInfo(userId);
		initAuthorization2userGrid(userId);
	};
	/**
	 * 加载用户基本信息.
	 */
	function loadUserInfo(userId) {
		Ccay.doGet("services/manage/security/userManage/findUserById/"+userId, "",function(user) {
			$S("#userId").val(user.id);
			$S("#DIS_userName").val(user.name);
			$S("#DIS_displayName").val(user.displayName);
			$S("#DIS_phone").val(user.phone);
		});
	}

	// 配置用户在群组默认的有效
	function initUserRoleMaxDay(userId) {
		var restPath = "services/ccay/security/userPermission/single/postponement";
		Ccay.doGet(restPath, '', function(data) {
					userMaxDay = data[0];
					initAuthorization2userGrid(userId);
				});
	}

	// 获取服务器时间
	function initSystemTime(userId) {
		Ccay.doGet("services/ccay/web/support/server/systemTime", '', function(data) {
					initTime = data.currentDate;
					initUserRoleMaxDay(userId);
				});
	}
	
	
	/**
	 * @description  打开view页面dialog 
	 * @param id 传入的参
	 */
	page.openRolePermissionView = function(id){
		Ccay.Page.register("ccay.security.role.roleOperationView","manage/security/role/roleOperationView.html");
		// 注册弹出框
		Ccay.Common.openPage("ccay.security.label.viewPermission","ccay.security.role.roleOperationView", {
			width : 800,
			height : 480,
			buttons : [{
				text : "ccay.common.label.close",
				onClick : function() {
					// 关闭方法
					ccay.security.role.roleOperationView.closeDialog();
				}
			}]
		}, function() {
			// 初始化方法
			ccay.security.role.roleOperationView.initById(id);
		});
	};
	
	/**
	 * @description  打开view页面dialog 
	 * @param id 传入的参
	 */
	page.openProgramView=function(id){
		Ccay.Page.register("ccay.security.program.view","manage/security/program/programView.html");
		Ccay.Common.openPage("ccay.program.label.programPreview","ccay.security.program.view",	
				 { width:585,
		           height:380,
		           buttons : [{
		           		type:"imgBtn",
			      		icon:"cancel",
			      		text : "ccay.common.label.close", 
			      		cls : "ccay-icon", 
						onClick : function() {
							ccay.security.program.view.closeDialog();
						}
					}]
		         },
				function(){
			        ccay.security.program.view.init(id);
		        }
		);
	};

	// 初始化Grid.
	function initAuthorization2userGrid(userId) {
		//Role Render
		var roleNameRenderer = Ccay.UI.Renderer.create({
			//初始化时，返回设置页面显示格式
			getFormat : function(field, format) {
				return "${#ccay.security.user.EditAuthorization2User.showRoleName(roleId,roleName)}";
			},
			//编辑之前，返回获取该列的值
			getValue : function(target) {
				return {
					value : target.attr('val') || "",
					text : target.text() || ""
				};
			},
			//编辑之后，设置页面显示的格式
			render : function(target, valueObj, format) {
				valueObj = Ccay.Format.toValueObj(valueObj, format ? format.data : null)
				target.attr('val', valueObj.value).html(page.showRoleName(valueObj.value,valueObj.text));
			}
		});
		//Program Render
		var programNameRenderer = Ccay.UI.Renderer.create({
			//初始化时，返回设置页面显示格式
			getFormat : function(field, format) {
				return "${#ccay.security.user.EditAuthorization2User.showProgramName(programId,programName)}";
			},
			//编辑之前，返回获取该列的值
			getValue : function(target) {
				return {
					value : target.attr('val') || "",
					text : target.text() || ""
				};
			},
			//编辑之后，设置页面显示的格式
			render : function(target, valueObj, format) {
				valueObj = Ccay.Format.toValueObj(valueObj, format ? format.data : null)
				target.attr('val', valueObj.value).html(page.showProgramName(valueObj.value,valueObj.text));
			}
		});

		var gridOptions = {
			// 设置高度
			height : 300,
			// 是否分页
			showPager : false,
			// 是否可编辑
			editMode : true,

			columns : [
			{
				header : "ccay.common.label.status",
				width : 40,
				sortable : false,
				resizable : false,
				freezeable : true,
				cssName : "center",
				editable : false,
				content : "${#setProcess(data)}"
			}, {
				columnType : 'select',
				multi : true
			}, {
				field:"roleName",
				valueField : 'roleId',
				width : 210,
				header : "ccay.security.label.roleName",
				renderer : roleNameRenderer,
				editorOp : {
					type : "suggest",
					conf : Role.suggestRoleEditOpt()
				},
				rule : {
					required : true
				}
			}, {
				field:"programName",
				valueField : 'programId',
				width : 210,
				header : "ccay.security.label.datascope",
				renderer : programNameRenderer,
				editorOp : {
					type : 'popbox',
					conf : Program.suggestPopupEditOpt()
				},
				rule : {
					required : true
				}
			}, {
				field : 'startDate',
				width : 153,
				cssName : "center",
				headCss: "editor",
				header : "ccay.common.label.beginDate",
				type : 'date',
				rule : {
					required : true,
					dateCompare : ["endDate", 0, "#authorization2userGrid"]
				}
			}, {
				field : 'endDate',
				width : 153,
				cssName : "center",
				headCss: "editor",
				header : $i18n("ccay.common.label.endDate"),
				type : 'date',
				rule : {
					required : true,
					dateCompare : ["startDate", 1, "#authorization2userGrid"]
				},
				editorOp : {
					wmindate : initTime
				}
			}],
			// 设置igrid的ajax请求参数，url属性获取数据源的链接地址
			ajax : {
				url : "services/manage/security/permissionManage/findProgramRolesByUserId/" + userId
			},
			operation : {
				insert : {
					btn : '#authBtnAdd',
					defaultRow : {
						startDate : Ccay.Format.toDate(initTime)
					}
				},
				// 设置igrid的标记删除数据操作
				del : {
					// 指定标记删除按钮的id
					btn : '#authBtnDelete',
					// 指定取消标记删除按钮的id
					undoBtn : '#authBtnUndoDel'
				},
				save : {
					fnBeforeSave: function(data, ajax, grid, optOp){
						//debugger;
						Ccay.doPut({
				 			async:false,
				 			url:"services/manage/security/permissionManage/userAuthz/"+$S("#userId").val(),
				 			data : data,
				 			success:function(result){
				 				if(result.RoleProgramUniqueFail){
				 					Ccay.UI.showMessage($i18n("ccay.common.message.duplicate").formatValue(result.RoleProgramUniqueFail.join(",")), 'error');
				 				}else{
								Ccay.UI.topBox($i18n("ccay.common.message.success"));
								authorization2userGrid.clearCache();
								authorization2userGrid.reload(true,true,true);
				 				}
				 			}			
				 		});
				 		//不在继续保存操作
				 		return false;
					},
					btn : '#authBtnSave',
					ajax : {//fnBeforeSave已处理 这里留空元素
//						type : "PUT",
//						url:"services/manage/security/permissionManage/userAuthz/"+$S("#userId").val()
					}
				}
			}
		};
		if (!Ccay.DataHelper.isEmpty(userId)) {
			// 初始化Grid
			$S("#authorization2userGrid").igrid(gridOptions);
			authorization2userGrid = $S("#authorization2userGrid").manager();
		}

	};
	/**
	 * 关闭打开的tab
	 */
	page.closeTab = function(isReload) {
		var records = $("#authorization2userGrid").manager();
		var allDifferentRecords = records.getDeletedRecords().length + records.getUpdatedRecords().length + records.getInsertedRecords().length;
		// 如果界面做了任何修改就弹出提示框
		if (allDifferentRecords != 0) {
			var message = $i18n("ccay.security.label.leaveComform.message");
			Ccay.UI.confirm(message, function(flag) {
						if (flag) {
							page.closeAllTab();
						}
					});
		} else {
			page.closeAllTab();
		}
	};


	setProcess = function(record) {
		var htmlDate = "";
		if (!Ccay.DataHelper.isEmpty(record.roleId)) {
			var currentDate = Ccay.Format.toDate(initTime).getTime();
			if (currentDate < Ccay.Format.toDate(record.startDate).getTime()) {
				htmlDate = "<span class='icon effective'></span>";
			} else if (currentDate > Ccay.Format.toDate(record.endDate).getTime()) {
				htmlDate = "<span class='icon expired'></span>";
			} else if (record.endDate && ((Ccay.Format.toDate(record.endDate).getTime()) - currentDate) / (1000 * 60 * 60 * 24) <= (overdueDay - 1)) {
				htmlDate = "<span class='icon toExpire'></span>";
			}
		}
		return htmlDate;
	};

});